package com.hzw.saas.common.security.adapter;

import cn.hutool.core.collection.CollectionUtil;
import com.hzw.saas.common.security.config.customer.SaasSecurityConfig;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

/**
 * spring security默认配置
 *
 * @author zzl
 * @since 12/21/2020
 */
@Configuration
@Order(95)
@AllArgsConstructor
@Slf4j
public class WebSecurityConfigAdapter extends WebSecurityConfigurerAdapter {
    private final SaasSecurityConfig securityConfig;

    /**
     * @return AuthenticationManager bean
     */
    @Bean
    @SneakyThrows
    @Override
    public AuthenticationManager authenticationManagerBean() {
        return super.authenticationManagerBean();
    }

    /**
     * @return PasswordEncoder bean
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    /**
     * 静态资源适合放这里
     *
     * @param web web
     * @throws Exception e
     */
    @Override
    public void configure(WebSecurity web) {
        List<String> urls = securityConfig.ignoreStaticUrls();
        if(CollectionUtil.isEmpty(urls)) {
            return;
        }
        web.ignoring().antMatchers(urls.toArray(new String[] {}));
    }

}
